package com.go.where.family.api.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alipay.api.internal.util.AlipaySignature;
import com.go.where.family.api.constants.Constant;
import com.go.where.family.api.scoket.Head;
import com.go.where.family.api.scoket.SocketDTO;
import com.go.where.family.api.scoket.TransmissionCode;
import com.go.where.family.api.server.HttpServerStartMain;
import com.go.where.family.api.utils.CommonUtil;
import com.go.where.family.api.utils.IpUtil;
import com.go.where.family.api.utils.ServletUtil;
import com.go.where.family.api.vo.OrderVo;
import com.google.gson.Gson;

/**
 * 支付宝支付状态回调
 * 
 * @description
 * @author
 * @date
 */
public class AlipayCallbackServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(AlipayCallbackServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		Map<String, String> paraMap = createParameterMap(req);
		ServletUtil.logReqParams(req, "支付宝异步通知");
		log.info("支付宝异步通知：paraMap：" + paraMap);
		try {
			boolean flag = AlipaySignature.rsaCheckV1(paraMap,
					HttpServerStartMain.getValue("alipay.public.key"), "UTF-8");
			if (flag) {// 数据校验成功

				OrderVo vo = new OrderVo();
				vo.setOrderId(paraMap.get("out_trade_no"));
				vo.setTpPayNo(paraMap.get("trade_no"));
				vo.setTradeStatus(paraMap.get("trade_status"));
				vo.setTotalAmount(paraMap.get("total_fee"));
				vo.setPayType("1");
				SocketDTO dto = sendMessage(vo, req);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				// String resMsg = head.getResponseMessage();
				String body = dto.getBody();
				if (TransmissionCode.SUCCESS.getCode().equals(resCode)) {
					// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
					if (StringUtils.isNotBlank(body)) {
						boolean res = gson.fromJson(body, Boolean.class);
						if (res) {
							ServletUtil.writeResJsonStr(resp, "success");
						} else {
							ServletUtil.writeResJsonStr(resp, "failure");
						}
					} else {
						ServletUtil.writeErrorStr(resp);
					}
				} else {
					log.error("内部通信异常，" + head.getResponseMessage());
					ServletUtil.writeResJsonStr(resp, "failure");
				}

			} else {
				log.error("支付宝异步通知，验签失败");
				ServletUtil.writeResJsonStr(resp, "failure");
			}
		} catch (Exception e) {
			log.error("异常信息", e);
			ServletUtil.writeResJsonStr(resp, "failure");
		}
	}

	public static void main(String[] args) throws Exception {
		String sign = "c+5JCsuwsW1YRnXxabrgvaw+B8DKh2JGuDKiCJpbwwNzanfnVaU5Pfl/l210Yc67L9U4gGVe/T5ci/ea4BSR3DyeEfkO/LnKVaf8FrUHpLoPYvhSN4uk9UiHXq74eO8oG4v4f9Ex2jOEhm4sJasaqOxBX7p5UMsTPJ2T6eQykwg=";
		// sign = URLEncoder.encode(sign, "utf-8");
		String sour = "body=去哪捐助&buyer_email=15968879083&buyer_id=2088502947429246&discount=0.00&gmt_create=2016-09-07 15:50:26&is_total_fee_adjust=Y&notify_id=3e054457d97a45578d085188d7d5109huq&notify_time=2016-09-07 16:04:08&notify_type=trade_status_sync&out_trade_no=2016090700000022&payment_type=1&price=0.01&quantity=1&seller_email=17767173739@163.com&seller_id=2088021054446798&subject=去哪捐助&total_fee=0.01&trade_no=2016090721001004240211206318&trade_status=WAIT_BUYER_PAY&use_coupon=N";
		boolean s = AlipaySignature.rsaCheckContent(sour, sign,
				HttpServerStartMain.getValue("alipay.public.key"), "utf-8");

		System.out.println(s);
	}

	private Map<String, String> createParameterMap(HttpServletRequest req) {
		Map<String, String> map = new HashMap<String, String>();
		String notify_time = req.getParameter("notify_time");
		map.put("notify_time", notify_time);
		String notify_type = req.getParameter("notify_type");
		map.put("notify_type", notify_type);
		String notify_id = req.getParameter("notify_id");
		map.put("notify_id", notify_id);
		String sign_type = req.getParameter("sign_type");
		map.put("sign_type", sign_type);
		String sign = req.getParameter("sign");
		map.put("sign", sign);
		String trade_no = req.getParameter("trade_no");
		map.put("trade_no", trade_no);
		String out_trade_no = req.getParameter("out_trade_no");
		map.put("out_trade_no", out_trade_no);
		String subject = req.getParameter("subject");
		if (StringUtils.isNotBlank(subject)) {
			map.put("subject", subject);
		}
		String payment_type = req.getParameter("payment_type");
		if (StringUtils.isNotBlank(payment_type)) {
			map.put("payment_type", payment_type);
		}
		String trade_status = req.getParameter("trade_status");
		if (StringUtils.isNotBlank(trade_status)) {
			map.put("trade_status", trade_status);
		}
		String seller_id = req.getParameter("seller_id");
		if (StringUtils.isNotBlank(seller_id)) {
			map.put("seller_id", seller_id);
		}
		String seller_email = req.getParameter("seller_email");
		if (StringUtils.isNotBlank(seller_email)) {
			map.put("seller_email", seller_email);
		}
		String buyer_id = req.getParameter("buyer_id");
		if (StringUtils.isNotBlank(seller_id)) {
			map.put("buyer_id", buyer_id);
		}
		String buyer_email = req.getParameter("buyer_email");
		if (StringUtils.isNotBlank(buyer_email)) {
			map.put("buyer_email", buyer_email);
		}
		String total_fee = req.getParameter("total_fee");
		if (StringUtils.isNotBlank(total_fee)) {
			map.put("total_fee", total_fee);
		}
		String quantity = req.getParameter("quantity");
		if (StringUtils.isNotBlank(quantity)) {
			map.put("quantity", quantity);
		}
		String price = req.getParameter("price");
		if (StringUtils.isNotBlank(price)) {
			map.put("price", price);
		}
		String body = req.getParameter("body");
		if (StringUtils.isNotBlank(body)) {
			map.put("body", body);
		}
		String gmt_create = req.getParameter("gmt_create");
		if (StringUtils.isNotBlank(gmt_create)) {
			map.put("gmt_create", gmt_create);
		}
		String gmt_payment = req.getParameter("gmt_payment");
		if (StringUtils.isNotBlank(gmt_payment)) {
			map.put("gmt_payment", gmt_payment);
		}
		String is_total_fee_adjust = req.getParameter("is_total_fee_adjust");
		if (StringUtils.isNotBlank(is_total_fee_adjust)) {
			map.put("is_total_fee_adjust", is_total_fee_adjust);
		}
		String use_coupon = req.getParameter("use_coupon");
		if (StringUtils.isNotBlank(use_coupon)) {
			map.put("use_coupon", use_coupon);
		}
		String discount = req.getParameter("discount");
		if (StringUtils.isNotBlank(discount)) {
			map.put("discount", discount);
		}
		String refund_status = req.getParameter("refund_status");
		if (StringUtils.isNotBlank(refund_status)) {
			map.put("refund_status", refund_status);
		}
		String gmt_refund = req.getParameter("gmt_refund");
		if (StringUtils.isNotBlank(gmt_refund)) {
			map.put("gmt_refund", gmt_refund);
		}

		return map;
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(OrderVo vo, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.ORDER_CALLBACK);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, vo);
	}

}
